<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简单聊天室</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #e9ecef;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }

        .container {
            width: 100%;
            max-width: 600px;
            background-color: #ffffff;
            border-radius: 10px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .chat-window {
            background-color: #f8f9fa;
            border-radius: 10px 10px 0 0;
            overflow-y: auto;
            height: 400px;
            padding: 20px;
            border-bottom: 1px solid #ddd;
        }

        .message {
            padding: 10px;
            border-radius: 15px;
            margin-bottom: 10px;
            position: relative;
            max-width: 80%;
            word-wrap: break-word;
            transition: background-color 0.3s, transform 0.2s;
        }

        .message:hover {
            transform: scale(1.02);
        }

        .message.system {
            background-color: #d1ecf1;
            color: #0c5460;
            align-self: flex-start;
            margin-right: auto;
        }

        .message.user {
            background-color: #c3e6cb;
            color: #155724;
            align-self: flex-end;
            margin-left: auto;
        }

        .input-area {
            display: flex;
            padding: 10px;
            background-color: #ffffff;
            border-top: 1px solid #ddd;
        }

        .input-area input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            font-size: 16px;
            transition: border-color 0.3s;
        }

        .input-area input:focus {
            border-color: #007bff;
            outline: none;
        }

        .input-area button {
            margin-left: 10px;
            padding: 10px 15px;
            background-color: #007bff;
            color: #ffffff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s, transform 0.2s;
        }

        .input-area button:hover {
            background-color: #0056b3;
            transform: scale(1.05);
        }

        /* 自定义滚动条 */
        .chat-window::-webkit-scrollbar {
            width: 8px;
        }

        .chat-window::-webkit-scrollbar-thumb {
            background: #007bff;
            border-radius: 10px;
        }

        .chat-window::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="chat-window" id="chatWindow"></div>
        <div class="input-area">
            <input type="text" id="messageInput" placeholder="输入消息..." />
            <button onclick="sendMessage()">发送</button>
        </div>
    </div>
    <script>
        // 发送消息的函数
        async function sendMessage() {
            const messageInput = document.getElementById('messageInput');
            const message = messageInput.value.trim();

            if (!message) {
                alert('消息不能为空！');
                return;
            }

            const data = { message };

            try {
                const response = await fetch('http://localhost:5000/api/chat', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(data)
                });

                if (response.ok) {
                    const result = await response.json();
                    messageInput.value = ""; // 清空输入框
                    updateChatWindow(result.greeting, 'system'); // 更新聊天窗口
                } else {
                    console.error('发送消息时出错:', response.status);
                }
            } catch (error) {
                console.error('发送消息时出错:', error);
            }
        }

        // 更新聊天窗口的函数
        function updateChatWindow(message, role) {
            if (!message || message.includes('undefined')) {
                return; // 不显示未定义消息
            }

            const chatWindow = document.getElementById('chatWindow');
            const messageElement = document.createElement('div');
            messageElement.classList.add('message', role);
            messageElement.innerHTML = `
                <div class="name">${role === 'system' ? 'System' : 'You'}</div>
                <div class="text">${message}</div>
            `;
            chatWindow.appendChild(messageElement);
            chatWindow.scrollTop = chatWindow.scrollHeight; // 滚动到最新消息
        }

        // 获取聊天记录并渲染到聊天窗口的函数
        async function fetchAndDisplayChatLog() {
            try {
                const response = await fetch('http://localhost:5000/api/chat_log');
                if (response.ok) {
                    const chatLog = await response.json();
                    document.getElementById('chatWindow').innerHTML = ''; // 清空聊天窗口
                    chatLog.forEach(line => {
                        const parts = line.split(', Message: ');
                        const ip = parts[0].split('IP: ')[1];
                        const text = parts[1];
                        updateChatWindow(text, ip === '0.0.0.0' ? 'system' : 'user');
                    });
                } else {
                    console.error('获取聊天记录时出错:', response.status);
                }
            } catch (error) {
                console.error('获取聊天记录时出错:', error);
            }
        }

        // 页面加载完成后获取聊天记录
        document.addEventListener('DOMContentLoaded', function() {
            fetchAndDisplayChatLog(); // 初始加载聊天记录
            setInterval(fetchAndDisplayChatLog, 2000); // 每 2 秒更新聊天记录
        });
    </script>
</body>
</html>